<template>
	<view class="store-poster">
		<view class="store-poster-canvas">
			<canvas id="poster" class="poster-canvas" canvas-id="poster" style="width: 600rpx; height: 888rpx;"></canvas>
			<view class="save" @click="savePoster" :style="{backgroundColor: '#f59359'}">保存到相册</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				store_id: '',
				QRcode: 'https://gengmeijia.oss-cn-shenzhen.aliyuncs.com/static/images/qrcode/2023-07-10/16889526443443.png',
				ctx: '',
				canvasW: '',
				canvasH: '',
				storeInfo: ''
			}
		},
		async onLoad(options) {
			this.store_id = options.store_id
		},
		onReady() {
			this.$nextTick(() => {
				this.OnCanvas()
			})
		},
		methods: {
			async OnCanvas() {
				uni.showLoading({
					title: '正在生成'
				})
				let storeInfo = await this.$u.api.StoreInfo({
					paramter: 1,
					store_id: this.store_id
				})
				this.storeInfo = storeInfo.datas[0]
				const {
					datas
				} = await this.$u.api.AddCustomerStoreQr({
					store_id: this.store_id
				})
				this.QRcode = datas
				this.ctx = uni.createCanvasContext('poster', this);
				this.canvasW = uni.upx2px(600);
				this.canvasH = uni.upx2px(900);
				this.ctx.setFillStyle('#FFFFFF');
				this.ctx.fillRect(0, 0, this.canvasW, this.canvasH)
				// 绘制工厂名称
				const factoryName = this.storeInfo.store_name
				this.ctx.setFillStyle('#000');
				this.ctx.font = 'bold nomal 18px Microsoft YaHei';
				this.ctx.textAlign = 'left'
				this.ctx.fillText(factoryName, uni.upx2px(56), uni.upx2px(108));
				// 绘制工厂LOGO
				const logo = await this.getImageInfo({
					imgSrc: this.storeInfo.store_logo
				});
				this.roundRectColor(this.ctx, uni.upx2px(480), uni.upx2px(96), uni.upx2px(60), logo.path);
				// 电话
				const phoneIcon = await this.getImageInfo({
					imgSrc: `https://master.shengejiaju.cn/web/static/new-shop/icon10.png`
				});
				this.ctx.drawImage(phoneIcon.path, uni.upx2px(56), uni.upx2px(179), uni.upx2px(32), uni.upx2px(32));
				this.ctx.setFillStyle('#7E7E7E');
				this.ctx.font = 'nomal nomal 12px Microsoft YaHei';
				this.toFormateStr(
					this.ctx,
					this.storeInfo.phone,
					uni.upx2px(300),
					1,
					uni.upx2px(96),
					uni.upx2px(204),
					uni.upx2px(24)
				)
				// 地址
				const addressIcon = await this.getImageInfo({
					imgSrc: `https://master.shengejiaju.cn/web/static/new-shop/icon11.png`
				});
				this.ctx.drawImage(addressIcon.path, uni.upx2px(56), uni.upx2px(227), uni.upx2px(32), uni.upx2px(32));
				this.ctx.setFillStyle('#7E7E7E');
				this.ctx.font = 'nomal nomal 12px Microsoft YaHei';
				this.toFormateStr(
					this.ctx,
					this.storeInfo.address,
					uni.upx2px(400),
					2,
					uni.upx2px(96),
					uni.upx2px(254),
					uni.upx2px(24)
				)
				// 绘制二维码
				const QRcodeImgInfo = await this.getImageInfo({
					imgSrc: this.QRcode
				});
				this.ctx.drawImage(QRcodeImgInfo.path, uni.upx2px(160), uni.upx2px(418), uni.upx2px(280), uni.upx2px(280));
				// 绘制二维码提示
				const tips = '长按或扫描二维码进入店铺'
				this.ctx.setFillStyle(this.activeColor);
				this.ctx.font = 'bold nomal 12px Microsoft YaHei';
				this.ctx.textAlign = 'center'
				this.ctx.fillText(tips, uni.upx2px(300), uni.upx2px(740));
				//延迟后渲染至canvas上
				setTimeout(() => {
					this.ctx.draw();
					uni.hideLoading()
				}, 600);
			},
			async getImageInfo({
				imgSrc
			}) {
				return new Promise((resolve, errs) => {
					if(!imgSrc){
						errs('图片路径不存在');
						uni.hideLoading()
						return
					}
					if (imgSrc.indexOf('https') != -1) {
						uni.downloadFile({
							url: imgSrc,
							success: function(res) {
								uni.getImageInfo({
									src: res.tempFilePath,
									success: function(image) {
										resolve(image);
									},
									fail(err) {
										uni.showToast({
											title: '生成失败，请退出重试',
											icon: 'none',
											duration: 1500
										})
										errs(err);
									}
								});
							}
						})
					} else {
						uni.getImageInfo({
							src: imgSrc,
							success: function(image) {
								resolve(image);
							},
							fail(err) {
								uni.showToast({
									title: '生成失败，请退出重试',
									icon: 'none',
									duration: 1500
								})
								errs(err);
							}
						});
					}
				});
			},
			async roundRectColor(ctx, x, y, r, img) { //绘制圆角矩形（纯色填充）
				ctx.save();
				let size = 2 * r;
				ctx.arc(x, y, r, 0, 2 * Math.PI);
				ctx.clip();
				ctx.drawImage(img, x - r, y - r, size, size);
				ctx.restore();
			},
			toFormateStr(ctx, str, draw_width, lineNum, startX, startY, steps) {
				console.log(str)
				var strWidth = ctx.measureText(str).width; // 测量文本源尺寸信息（宽度）
				var startpoint = startY,
					keyStr = '',
					sreLN = strWidth / draw_width;
				var liner = Math.ceil(sreLN); // 计算文本源一共能生成多少行
				let strlen = parseInt(str.length / sreLN); // 等比缩放测量一行文本显示多少个字符
				// 若文本不足一行，则直接绘制，反之大于传入的最多行数（lineNum）以省略号（...）代替
				if (strWidth < draw_width) {
					ctx.textAlign = 'left'
					ctx.fillText(str, startX, startpoint);
				} else {
					for (var i = 1; i < liner + 1; i++) {
						let startPoint = strlen * (i - 1);
						if (i < lineNum || lineNum == -1) {
							keyStr = str.substr(startPoint, strlen);
							ctx.textAlign = 'left'
							ctx.fillText(keyStr, startX, startpoint);
						} else {
							keyStr = str.substr(startPoint, strlen - 2) + '...';
							ctx.textAlign = 'left'
							ctx.fillText(keyStr, startX, startpoint);
							break;
						}
						startpoint = startpoint + steps;
					}
				}
			},
			savePoster() {
				let _this = this
				uni.showLoading({
					title: '正在保存',
					mask: true
				})
				uni.canvasToTempFilePath({
					canvasId: 'poster',
					// width: uni.upx2px(600),
					// height: uni.upx2px(900),
					// destWidth: uni.upx2px(600),
					// destHeight: uni.upx2px(900),
					success: (data) => {
						uni.hideLoading()
						// #ifdef MP-WEIXIN
						uni.getSetting({
							withSubscriptions: true,
							success: (scope) => {
								if (!scope.authSetting['scope.writePhotosAlbum']) {
									uni.authorize({
										scope: 'scope.writePhotosAlbum',
										success: () => {
											uni.saveImageToPhotosAlbum({
												filePath: data.tempFilePath,
												success(saveRes) {
													uni.showToast({
														icon: 'none',
														title: '保存成功，请在相册中查看',
														duration: 1500
													})
												},
											})
										},
										fail: () => {
											uni.showModal({
												title: '温馨提示',
												content: '开启相册授权后才能保存图片，是否前往开启?',
												success: (res) => {
													if (res.confirm) {
														uni.openSetting()
													}
												}
											})
										}
									})
								} else {
									uni.saveImageToPhotosAlbum({
										filePath: data.tempFilePath,
										success(saveRes) {
											uni.showToast({
												icon: 'none',
												title: '保存成功，请在相册中查看',
												duration: 1500
											})
										},
									})
								}
							}
						})
						// #endif
					},
					fail: () => {
						uni.showToast({
							icon: 'none',
							title: '海报生成失败，请重试'
						})
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.store-poster {
		.store-poster-canvas {
			display: flex;
			align-items: center;
			flex-direction: column;
			padding-top: 80rpx;

			canvas {
				box-shadow: 0px 4rpx 24rpx 0px rgba(0, 0, 0, 0.10);
			}

			.save {
				width: 600rpx;
				height: 80rpx;
				border-radius: 8rpx;
				color: #FFF;
				text-align: center;
				line-height: 80rpx;
				font-weight: bold;
				margin-top: 40rpx;
			}
		}
	}
</style>